package pci.recommend

import collection.mutable.{HashSet, HashMap, Map}
import dispatch._

/**
 * Collect data from Delicious and put then into preference man.
 *
 * zhu.tan@gmail.com
 * 09-Jul-2009
 */

object CoDelicious {
  val h = new Http

  def initialPrefMap(tag: String, count : Int) = {
    val prefs = new HashMap[String, Map[String, Double]]()
    // get the top popular posts for a tag
    for (u <- h(Popular(tag).urls) take count) {
      Thread.sleep(500)    // so that Delicious will not block the call due to the high frequency requests.
      // find users who posted to this url
      for (p <- h(Url(u).users) take count ) {
        prefs(p) = new HashMap[String, Double]()
      }
    }
    prefs
  }

  def fillItems(prefs: Map[String, Map[String, Double]]) = {
    val all_items = new HashSet[String]()
    // Find Links posted by all users
    for (user <- prefs.keys) {
      for (url <- h(User(user).urls)) {
        prefs(user) += (url -> 1.0)
        all_items += url
      }
    }
    // fill in missing items with 0
    for ( ratings <- prefs.values ) {
      for (item <- all_items) {
        if (!(ratings.keys.contains(item))) {
          ratings += (item -> 0.0);
        }
      }
    }
    prefs
  }

}